const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
const formatDate = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  return [year, month, day].map(formatNumber).join('-');
}
const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
//公共js，主要做表单验证，以及基本方法封装
const utils = {
  isNullOrEmpty: function (value) {
    //是否为空
    return (value === null || value === '' || value === undefined) ? true : false;
  },
  trim: function (value) {
    //去空格
    return value.replace(/(^\s*)|(\s*$)/g, "");
  },
  trimAll: function (str, is_global){
    // 去所有的空格
    var result;
    result = str.replace(/(^\s+)|(\s+$)/g, "");
    if (is_global.toLowerCase() == "g") {
      result = result.replace(/\s/g, "");
    }
    return result;
  },
  isMobile: function (value) {
    //是否为手机号
    return /^(?:13\d|14\d|15\d|16\d|17\d|18\d|19\d)\d{5}(\d{3}|\*{3})$/.test(value);
  },
  isFloat: function (value) {
    //金额，只允许保留两位小数
    return /^([0-9]*[.]?[0-9])[0-9]{0,1}$/.test(value);
  },
  isNum: function (value) {
    //是否全为数字
    return /^[0-9]+$/.test(value);
  },
  formatNum: function (num) {
    //格式化手机号码
    if (utils.isMobile(num)) {
      num = num.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2')
    }
    return num;
  },
  interfaceUrl: function () {
    //接口地址
    return "https://www.thorui.cn";
  },
  toast: function (text, duration, icon, success, fail) {
    wx.showToast({
      title: text,
      icon: icon ? icon : 'none',
      duration: duration || 2000,
      success:success,
      fail:fail
    })
  },
  isEmpty: function (value){
    return value == '' || value == 0 || value == undefined || value == null;
  },
  preventMultiple: function (fn, gapTime) {
    if (gapTime == null || gapTime == undefined) {
      gapTime = 200;
    }
    let lastTime = null;
    return function () {
      let now = +new Date();
      if (!lastTime || now - lastTime > gapTime) {
        fn.apply(this, arguments);
        lastTime = now;
      }
    }
  },
  request: function (url, postData, method, type, hideLoading) {
    //接口请求
    if (!hideLoading) {
      wx.showLoading({
        title: '请稍候...',
        mask: true
      })
    }
    return new Promise((resolve, reject) => {
      wx.request({
        url: this.interfaceUrl() + url,
        data: postData,
        header: {
          'content-type': type ? 'application/x-www-form-urlencoded' : 'application/json'
        },
        method: method, //'GET','POST'
        dataType: 'json',
        success: (res) => {
          !hideLoading && wx.hideLoading()
          resolve(res.data)
        },
        fail: (res) => {
          !hideLoading && this.toast("网络不给力，请稍后再试~")
          //wx.hideLoading()
          reject(res)
        }
      })
    })
  },
  uploadFile: function (src) {
    const that = this
    wx.showLoading({
      title: '请稍候...',
      mask: true
    })
    return new Promise((resolve, reject) => {
      const uploadTask = wx.uploadFile({
        url: 'http://39.108.124.252:8081/fileServce/file/ ', //测试地址,暂不使用
        filePath: src,
        name: 'file',
        header: {
          'content-type': 'multipart/form-data'
        },
        formData: {},
        success: function (res) {
          wx.hideLoading()
          let d = JSON.parse(res.data)
          if (d.code === 1) {
            let fileObj = JSON.parse(d.data)[0];
            //文件上传成功后把图片路径数据提交到服务器，数据提交成功后，再进行下张图片的上传
            resolve(fileObj)
          } else {
            that.toast(res.message);
          }
        },
        fail: function (res) {
          reject(res)
          wx.hideLoading();
          that.toast(res.message);
        }
      })
    })
  },

   // 显示失败提示
 showModel :function (title, content)  {
  wx.hideToast();
  wx.showModal({
    title,
    content: content,
    showCancel: false
  });
}
}

module.exports = {
  formatTime: formatTime,
  formatDate: formatDate,
  isNullOrEmpty: utils.isNullOrEmpty,
  toast: utils.toast,
  isMobile: utils.isMobile,
  trimAll: utils.trimAll,
  isEmpty: utils.isEmpty,
  trim: utils.trim,
  showModel:utils.showModel
}
